package com.xch.sboot.web.api.common;

import cn.hutool.core.io.IoUtil;
import com.xch.sboot.common.exception.BusinessException;
import com.xch.sboot.common.response.Result;
import com.xch.sboot.config.login.NoNeedLogin;
import com.xch.sboot.persistence.domain.common.File;
import com.xch.sboot.service.common.FileService;
import com.xch.sboot.service.common.dto.FileDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @author xch
 * 2022/12/30 15:34
 */
@Api(tags = "文件")
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件单个上传")
    @PostMapping("/upload")
    public Result<FileDTO> upload(@RequestParam(name = "file") MultipartFile file) {
        try (InputStream is = file.getInputStream();
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            IoUtil.copy(is, os);
            byte[] bytes = os.toByteArray();
            FileDTO fileDTO = fileService.storeFile(bytes, Objects.requireNonNull(file.getOriginalFilename()), file.getContentType());
            return Result.newR(fileDTO);
        } catch (IOException e) {
            log.error("文件上传发生异常:{}", e.getMessage());
            throw new BusinessException("文件上传失败！");
        }
    }

    @ApiOperation("文件路径")
    @GetMapping("/{id}")
    @NoNeedLogin
    public void getFile(@PathVariable(name = "id") String id, HttpServletResponse response) {
        try {
            if (StringUtils.isEmpty(id)) {
                throw new BusinessException("文件ID不能为空！");
            }
            File file = fileService.getFileData(id);
            String oldName = URLEncoder.encode(file.getOldname(), "UTF-8");
            oldName = URLDecoder.decode(oldName, "ISO8859_1");
            response.setHeader("Content-disposition", "attachment; filename=" + oldName);
            response.setContentType(file.getContentType());
            OutputStream os = response.getOutputStream();
            fileService.getFileStream(file.getFullpath(), os);
            response.flushBuffer();
        } catch (IOException ex) {
            log.error("getFile error {}", ex.getMessage());
            response.setStatus(404);
        }
    }

}
